<!-- 事件日志 -->
<template>
  <div class="dashboard-editor-container">
    <div style="display:flex;justify-content:space-between;">
      <partitionTree :nodeData="nodeData" :expandArray="expandArray" :addTemplate="false" :defaultExpandAll="false" dialogName="WinService"
        @handleNodeClick="handleNodeClick" ref="partitionTree" @toggleVisibility="toggleVisibility">
      </partitionTree>
      <div :style="{ width: containerWidth }" class="box"
        style="background:#fff;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
        <el-row style="background: #fff; padding: 16px 16px 0;">
          <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"></connsearch>
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }"
            style="margin:0 0 16px 0;">
            <el-tabs type="border-card" v-model="tabTitle2" @tab-click="tabClick2">
              <el-tab-pane key="概要分析" label="概要分析" name="概要分析" lazy>
                <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
                  <el-table-column label="序号" width="60" type="index"
                    :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
                  <el-table-column label="服务名称" show-overflow-tooltip prop="ServiceName" width="180px"></el-table-column>
                  <el-table-column label="服务描述" show-overflow-tooltip prop="Descp"></el-table-column>
                  <el-table-column label="文件路径" show-overflow-tooltip prop="FilePath"></el-table-column>
                  <el-table-column label="服务启动类型" show-overflow-tooltip prop="StartTypeTxt"
                    width="120px"></el-table-column>
                  <el-table-column label="服务状态" show-overflow-tooltip prop="StatusTxt" width="120px"></el-table-column>
                  <el-table-column label="涉及资产" prop="DevCount" show-overflow-tooltip width="120px"></el-table-column>
                  <el-table-column label="操作" width="120px" fixed="right">
                    <template slot-scope="scope">
                      <el-button size="mini" type="success" @click="detailsChange(scope.row)">涉及资产</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
                  :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
                </el-pagination>
              </el-tab-pane>
              <el-tab-pane key="涉及资产" label="涉及资产" name="涉及资产" lazy>
                <el-table stripe border :data="tableData2" style="width: 100%; margin-top: 15px">
                  <el-table-column label="序号" width="60" type="index"
                    :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
                  <el-table-column label="部门" show-overflow-tooltip prop="Department" width="120px"></el-table-column>
                  <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" width="160px"></el-table-column>
                  <el-table-column label="使用者" show-overflow-tooltip prop="UserName" width="120px"></el-table-column>
                  <el-table-column label="服务名称" show-overflow-tooltip prop="ServiceName" width="180px"></el-table-column>
                  <el-table-column label="服务描述" show-overflow-tooltip prop="Descp"></el-table-column>
                  <el-table-column label="文件路径" show-overflow-tooltip prop="FilePath"></el-table-column>
                  <el-table-column label="服务启动类型" show-overflow-tooltip prop="StartTypeTxt"
                    width="120px"></el-table-column>
                  <el-table-column label="服务状态" show-overflow-tooltip prop="StatusTxt" width="120px"></el-table-column>
                </el-table>
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
                  :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
                </el-pagination>
              </el-tab-pane>
              <el-tab-pane key="审计策略" label="审计策略" name="审计策略" lazy>
                <div style="display:flex; justify-content: space-between;align-items: center;">
                  <div>
                    <span style="font-size:14px; color:#606266">检测到新的服务自动产生事件：
                      <el-radio v-model="DefaultEvent" :label="1">产生事件</el-radio>
                      <el-radio v-model="DefaultEvent" :label="0">不产生事件</el-radio>
                    </span>
                  </div>
                  <div>
                    <el-button type="primary" @click="checkAll">全选</el-button>
                    <el-button type="primary" @click="submit">保存</el-button>
                  </div>
                </div>
                <el-table stripe border :data="tableData3" style="width: 100%; margin-top: 15px">
                  <el-table-column label="序号" width="60" type="index"
                    :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
                  <el-table-column label="服务名称" show-overflow-tooltip prop="ServiceName"></el-table-column>
                  <el-table-column label="服务描述" show-overflow-tooltip prop="DisplayName"></el-table-column>
                  <el-table-column label="服务启动类型" show-overflow-tooltip prop="StartTypeTxt"></el-table-column>
                  <el-table-column label="服务状态" show-overflow-tooltip prop="StatusTxt"></el-table-column>
                  <el-table-column label="产生事件" width="120">
                    <template slot-scope="scope">
                      <el-switch v-model="scope.row.EnableEvent" :active-value="1" :inactive-value="0"></el-switch>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
                  :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
                </el-pagination>
              </el-tab-pane>
            </el-tabs>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import eventTrends from './components/BarChart3.vue'  //柱状图
import piechart from "./components/piechart.vue";
import { parseTime, GetDeviceTree2} from "@/utils/index.js";
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { connrequest } from "@/api/firstPage.js"
import partitionTree from "@/components/partitionTree";
export default {
  directives: { elDragDialog },
  components: { connsearch, eventTrends, piechart, partitionTree },
  data() {
    let that = this
    return {
      activeName: "",
      tabTitle2: "概要分析",
      pageNum: 1,
      pageSize: 10,
      total: 0,
      DefaultEvent: 1,
      tab: false,
      barchartData: { xAxis: [], series: [] },
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      nodeData: [],
      expandArray: [],
      containerWidth: 'calc(100% - 275px)',
      tableData: [],
      tableData2: [],
      tableData3: [],
      searchform: {},
      options: {},
      searchobj: {},
      resourceForm: {},
      DeviceObj: {},
      detailsobj: {},
      formOptions: [
        {
          col: 8,
          label: "服务名称",
          prop: "ServiceName",
          element: "el-input",
          placeholder: "请输入服务名称,支持模糊查询。",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.ServiceName = val
            },
          },
        },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = (Cookies.get('Zhuoguan_DefaultPageLength') || 10) * 1;

    let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
    let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
    let arr = [parseTime(startTime), '']
    this.formOptions.map(item => {
      if (item.label === '日期') {
        item.initValue = arr
      }
    })
    this.$set(this.searchform, 'timeRange', arr)
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initData()
  },
  methods: {
    parseTime,
    async initData(searchobj = {}) {
      try {
        const { DeviceTree } = await GetDeviceTree2('WinService', searchobj)
        this.nodeData = DeviceTree
        this.expandArray = [DeviceTree?.[0]?.Name]
      } catch (error) {
        this.$message.error('加载设备树数据失败');
      }
    },
    handleNodeClick(nodeData) {
      this.pageNum = 1
      this.nodeobj = { DepartmentID: nodeData.data.isDevice ? nodeData.data.DepartmentID : nodeData.data.ID, DeviceUUID: nodeData.data.isDevice ? nodeData.data.DeviceUUID : '' }
      this.echartsobj = {}
      this.detailsobj = {}
      this.getData({ ...this.searchobj, ...this.nodeobj })
    },
    toggleVisibility(isHidden) {
      if (isHidden)
        this.containerWidth = '100%';
      else
        this.containerWidth = 'calc(100% - 275px)';
    },
    async detailsChange(row) {
      this.pageNum = 1
      this.pageSize = 10
      this.tabTitle2 = '涉及资产'
      this.detailsobj = { ...this.searchobj, ...this.echartsobj, ServiceName: row.ServiceName, ...this.nodeobj }
      this.GetWinServiceDetail(this.detailsobj)
    },
    // 获取所有数据
    getData(searchobj = {}) {
      switch (this.tabTitle2) {
        case '概要分析':
          this.GetEventLog(searchobj)
          break;
        case '涉及资产':
          this.GetWinServiceDetail(searchobj)
          break;
        case '审计策略':
          this.GetWinServicePolicy(searchobj)
          break;
      }
    },
    tabClick2(row) {
      this.pageNum = 1
      this.pageSize = 10
      this.tabTitle = row.label
      this.searchobj = {}
      switch (row.label) {
        case '概要分析':
          this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
          break;
        case '涉及资产':
          this.GetWinServiceDetail({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
          break;
        case '审计策略':
          this.GetWinServicePolicy({ ...this.searchobj, ...this.nodeobj })
          break;
      }
    },
    // 获取事件日志列表
    async GetEventLog(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID,
          ServiceName: this.searchform.ServiceName,
          ...searchobj
        }
      }
      const res = await connrequest('GetWinService', data)
      res.Data = res.Data || []
      this.tableData = res.Data
      this.total = res.Paging.TotalCount || 0
    },
    async GetWinServiceDetail(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID,
          ServiceName: this.searchform.ServiceName,
          ...searchobj
        }
      }
      const res = await connrequest('GetWinServiceDetail', data)
      this.tableData2 = res.Data
      this.total = res.Paging.TotalCount || 0
    },
    async GetWinServicePolicy(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          ...searchobj
        }
      }
      const res = await connrequest('GetWinServicePolicy', data)
      this.tableData3 = res.Data.AutostartList
      this.DefaultEvent = res.Data.DefaultEvent
      this.total = res.Paging.TotalCount || 0
    },
    checkAll() {
      if (!Array.isArray(this.tableData3)) return;
      const hasAnyDisabled = this.tableData3.some(item => item.EnableEvent === 0);
      const newValue = hasAnyDisabled ? 1 : 0;
      this.tableData3.forEach(item => {
        item.EnableEvent = newValue;
      });
    },
    async submit() {
      const data = {
        Data: {
          DefaultEvent: this.DefaultEvent,
          WinServiceList: this.tableData3
        }
      }
      const res = await connrequest('EditWinServicePolicy', data)
      if (res.Status.StatusCode === 0) {
        this.$message.success('保存成功')
        this.GetWinServicePolicy()
      }
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = { ...val }
      this.searchform = { ...val }
      if (this.searchform.timeRange) {
        this.searchobj = { ...this.searchobj, StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData({ ...this.searchobj, ...this.nodeobj })
      this.initData({...this.searchobj})
    },
    // 重置
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
      let arr = [parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map(item => {
        if (item.label === "日期") {
          item.initValue = arr
        } else {
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.searchobj = {}
      this.detailsobj = {}
      this.nodeobj = {}
      this.$set(this.searchform, 'timeRange', arr)
      this.$refs.connsearch.addInitValue()
      this.getData()
      this.initData()
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageNum = 1
      switch (this.tabTitle2) {
        case '概要分析':
          this.GetEventLog({ ...this.searchobj, ...this.nodeobj })
          break;
        case '涉及资产':
          this.GetWinServiceDetail({ ...this.searchobj, ...this.nodeobj, ...this.detailsobj })
          break;
        case '审计策略':
          this.GetWinServicePolicy({ ...this.searchobj, ...this.nodeobj })
          break;
      }
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      switch (this.tabTitle2) {
        case '概要分析':
          this.GetEventLog({ ...this.searchobj, ...this.nodeobj })
          break;
        case '涉及资产':
          this.GetWinServiceDetail({ ...this.searchobj, ...this.nodeobj, ...this.detailsobj })
          break;
        case '审计策略':
          this.GetWinServicePolicy({ ...this.searchobj, ...this.nodeobj })
          break;
      }
    },
    handleClick() {
      this.tab = !this.tab
    }
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>